package titt.server.internal;

import titt.head.HTTPHead;
import titt.head.HeadFactory;
import titt.head.response.ResponseHead;
import titt.io.socket.TITTSocket;
import titt.key.TITTKey;
import titt.server.os.ObjectServer;
import titt.server.service.Service;
import titt.service.ServicePackage;
import titt.util.io.pipe.PipeListener;

public class ServerInternal {

	private final ObjectServer os;
	
	public ServerInternal(ObjectServer os) {
		this.os = os;
	}
	
	public void request(String serviceID, TITTSocket ts, HTTPHead head) throws Exception {
		Service s = os.getServerDatabase().get(serviceID);
		request(s, ts, head, null);		
	}
	
	public void request(TITTKey key, TITTSocket ts, HTTPHead head) throws Exception {
		request(key,ts,head,null);
	}

	public void request(TITTKey key, TITTSocket ts, HTTPHead head, PipeListener l) throws Exception {
		Service s = os.getServerDatabase().get(key);
		request(s, ts, head, l);
	}

	
	private void request(Service s, TITTSocket ts, HTTPHead head, PipeListener l) throws Exception {
		if(s == null) {
			ts.getHeadWriter().writeHead(new ResponseHead(404, os.addResponseHeaders(HeadFactory.EMPTY)));
			ts.close();
			return;
		}

		String packageID = s.getID() + ServicePackage.PACK_ID + "-" + os.generateID(false);
		
		s.deposit(new ServicePackage(packageID, head, ts, l));
		
	}
	
	public boolean unregister(String serviceID, int maxSec) throws Exception {
		if(maxSec > 0)
			os.getServerDatabase().get(serviceID).waitForCompletion(maxSec);

		Service s  = os.getServerDatabase().remove(serviceID);

		if(s != null) {
			s.stop();
			return true;
		}

		return false;
	}
	
}
